// components/find/pic-list.js
let isend = false // 是否是最后一页
let selectDate = '' // 当前的日期
let heightArr = []
let newHeightArr = []
let distanceTop = ''
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    newDate: Object,
    type: String, // 列表类型
  },

  options: {
    styleIsolation: 'apply-shared',
    multipleSlots: true,
  },

  /**
   * 组件的初始数据
   */
  data: {
    startDate: '2012-10',
    endDate: '',
    date: '',
    list: [],
    selectYear: '', // 当前年份
    selectMonth: '',  // 当前月份
    isend: false, // 是否是最后一页
    selectDate: '', // 当前的日期
    heightArr: [],
    newHeightArr: [],
    distanceTop: '',
    status: '',

    isRefreshing: false,//是否下拉刷新状态
    isFinish: false,//是否加载完全部数据
  },

  observers: {
    newDate(newVal) {
      if (newVal) {
        this.data.selectDate = newVal.YM
        this.setData({
          selectYear: newVal.year,
          selectMonth: newVal.month,
          endDate: newVal.YM
        })
      }
      
    }
  },

  lifetimes: {
    ready() {
      const newDate = this.getNewDate()
      wx.getSystemInfo({
        success: function (res) {
          distanceTop = res.windowHeight - 100
        }
      })
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 下拉刷新
    onRefresh() {
      if (this.data.selectDate === this.data.endDate) {
        // this.setData({
        //   status: 'refresh'
        // })
        this.data.status = 'refresh'
        this.gethp()
      } else {
        this.getNextMonth(this.data.selectDate).then(res => {
          this.setData({
            selectDate: res
          })
          this.data.status = 'nextRefresh'
          this.gethp()
        })
      }
    },
    // 上拉加载更多
    onLoadMore() {
      console.log('是否最后一页', this.data.isend, this.data.selectDate)
      if (!this.data.isend) {
        this.getPreMonth(this.data.selectDate).then(res => {
          this.setData({
            selectDate: res
          })
          this.gethp()
        })
      }
    },
    // 获取当前月份
    getNewDate() {
      const newDate = new Date()
      const year = newDate.getFullYear()
      let month = this.formatNumber(newDate.getMonth() + 1)
      const YM = year + '-' + month
      return {
        YM,
        year,
        month
      }
    },
    bindDateChange: function (e) {
      let date = e.detail.value
      this.setData({
        selectDate: date,
        status: 'choice',
        date
      })
      this.setTopTime(date)
      this.gethp()
    },
    // 获取列表数据
    /**
     * @params {String} status refresh：下拉刷新  choice：选择日期  nextRefresh：刷新下一个月份
     * 
    */
    gethp(val) {
      let type = val ? val : this.data.type
      let status = this.data.status
      this.setData({
        type: type
      })
      console.log('type::::::::', type)
      
      switch(type) {
        case 'pic':
          this.getPicData(status)
          break;
        case 'read':
          this.getReadData(status)
          break;
        case 'music':
          this.getMusicData(status)
          break;
      }
    },
    getMusicData(status) {
      if (this.data.isLoading) return false
      this.setData({
        alreadyLoadData: false,
        isLoading: true
      })
      wx.cloud.callFunction({
        name: 'finds',
        data: {
          date: this.data.selectDate,
          $url: 'music'
        }
      }).then(res => {
        console.log('res', res)
        this.data.heightArr.splice(0, this.data.heightArr.length)
        this.data.newHeightArr.splice(0, this.data.newHeightArr.length)
        if (status === 'choice') {
          this.data.list.splice(0, this.data.list.length)
        }
        if (status === 'refresh') {
          this.data.list.splice(0, 1)
        }
        if (status === 'nextRefresh') {
          this.setTopTime(this.data.selectDate)
        }
        let data = res.result.data
        let time, month
        if (res.result && data.length > 0) {
          month = res.result.date.substring(5, 7)
          time = res.result.date.substring(0, 7)
          // 减小data的空间，只取有效字段
          let newdata = data.map(item => {
            return {
              id: item.content_id,
              cover: item.cover,
              story_title: item.story_title,
              title: item.title,
              guide_word: item.guide_word,
              author: item.author.user_name
            }
          })
          if (status === 'refresh' || status === 'nextRefresh') {
            this.data.list.unshift({
              arr: newdata,
              hp_date: time,
              hp_month: month
            })
            this.setData({
              list: this.data.list
            })
          } else {
            let Length = this.data.list.length;
            this.setData({
              ['list[' + Length + ']']: {
                arr: newdata,
                hp_date: time,
                hp_month: month
              }
            })
          }
          this.createSelectorQuery().selectAll('.find_list').boundingClientRect((rects) => {
            rects.map((rect, index) => {
              this.data.heightArr.push({
                time: rect.dataset.date,
                height: rect.height
              })
            })
            this.setHeight()
          }).exec()
          // 判断是否是最后一页
          this.getPreMonth(this.data.selectDate).then(dd => {
            // this.data.isend = dd === this.data.startDate ? true : false
            this.setData({
              isend: dd === this.data.startDate ? true : false
            })
          })
        }
        // setTimeout(() => {
          this.setData({
            alreadyLoadData: true,
            isLoading: false,
            isRefreshing: false,
          })
        // }, 300)
        // if (this.data.list.length < 10) {
        //   this.onloadMore()
        // }
      })
    },
    getReadData(status) {
      if (this.data.isLoading) return false
      this.setData({
        alreadyLoadData: false,
        isLoading: true
      })
      wx.cloud.callFunction({
        name: 'finds',
        data: {
          date: this.data.selectDate,
          $url: 'essay'
        }
      }).then(res => {
        console.log('res', res)
        this.data.heightArr.splice(0, this.data.heightArr.length)
        this.data.newHeightArr.splice(0, this.data.newHeightArr.length)
        if (status === 'choice') {
          this.data.list.splice(0, this.data.list.length)
        }
        if (status === 'refresh') {
          this.data.list.splice(0, 1)
        }
        if (status === 'nextRefresh') {
          this.setTopTime(this.data.selectDate)
        }
        let data = res.result.data
        let time, month
        if (res.result && data.length > 0) {
          // 减小data的空间，只取有效字段
          let newdata = data.map(item => {
            time = item.hp_makettime.substring(0, 7)
            month = item.hp_makettime.substring(5, 7)
            return {
              id: item.content_id,
              hp_title: item.hp_title,
              guide_word: item.guide_word,
              author: item.author[0].user_name.substring(0, 6)
            }
          })
          if (status === 'refresh' || status === 'nextRefresh') {
            this.data.list.unshift({
              arr: newdata,
              hp_date: time,
              hp_month: month
            })
            this.setData({
              list: this.data.list
            })
          } else {
            let Length = this.data.list.length;
            this.setData({
              ['list[' + Length + ']']: {
                arr: newdata,
                hp_date: time,
                hp_month: month
              }
            })
          }
          this.createSelectorQuery().selectAll('.find_list').boundingClientRect((rects) => {
            rects.map((rect, index) => {
              this.data.heightArr.push({
                time: rect.dataset.date,
                height: rect.height
              })
            })
            this.setHeight()
          }).exec()
          // 判断是否是最后一页
          this.getPreMonth(this.data.selectDate).then(dd => {
            // this.data.isend = dd === this.data.startDate ? true : false
            this.setData({
              isend: dd === this.data.startDate ? true : false
            })
          })
        }
        // setTimeout(() => {
          this.setData({
            alreadyLoadData: true,
            isLoading: false,
            isRefreshing: false,
          })
        // }, 300)
      })
    },
    getPicData(status) {
      if (this.data.isLoading) return false
      this.setData({
        alreadyLoadData: false,
        isLoading: true
      })
      wx.cloud.callFunction({
        name: 'finds',
        data: {
          date: this.data.selectDate,
          $url: 'hp'
        }
      }).then(res => {
        console.log('res:::', res)
        this.data.heightArr.splice(0, this.data.heightArr.length)
        this.data.newHeightArr.splice(0, this.data.newHeightArr.length)
        if (status === 'choice') {
          this.data.list.splice(0, this.data.list.length)
        }
        if (status === 'refresh') {
          this.data.list.splice(0, 1)
        }
        if (status === 'nextRefresh') {
          this.setTopTime(this.data.selectDate)
        }
        let data = res.result.data
        let time
        if (res.result && data.length > 0) {
          // 减小data的空间，只取有效字段
          let newdata = data.map(item => {
            time = item.hp_makettime.substring(0, 7)
            return {
              id: item.hpcontent_id,
              hp_makettime: item.hp_makettime.substring(0, 10),
              hp_img_url: item.hp_img_url
            }
          })
          if (status === 'refresh' || status === 'nextRefresh') {
            this.data.list.unshift({
              arr: newdata,
              hp_date: time
            })
            this.setData({
              list: this.data.list
            })
          } else {
            let Length = this.data.list.length;
            this.setData({
              ['list[' + Length + ']']: {
                arr: newdata,
                hp_date: time
              }
            })
          }
          this.createSelectorQuery().selectAll('.find_list').boundingClientRect((rects) => {
            rects.map((rect, index) => {
              this.data.heightArr.push({
                time: rect.dataset.date,
                height: rect.height
              })
            })
            this.setHeight()
          }).exec()
          // 判断是否是最后一页
          this.getPreMonth(this.data.selectDate).then(dd => {
            this.setData({
              isend: dd === this.data.startDate ? true : false
            })
          })
        }
        // setTimeout(() => {
          this.setData({
            alreadyLoadData: true,
            isLoading: false,
            isRefreshing: false,
          })
        // }, 300)
        
      })
    },
    // 
    setHeight() {
      // console.log('heightArr:::::', this.data.heightArr)
      for (let i in this.data.heightArr) {
        this.data.newHeightArr.push({
          time: this.data.heightArr[i].time,
          height: this.getsum(i, this.data.heightArr)
        })
      }
      // console.log('newHeightArr::::::::::', this.data.newHeightArr)
    },
    // 获取当前节点距离顶部的高度
    getsum(index, arr) {
      let sum = 0
      for (let i in arr) {
        sum += arr[i].height
        if (i == index) {
          return sum
        }
      }
    },
    // 上一个月份
    getPreMonth(date) {
      return new Promise(resolve => {
        var arr = date.split('-');
        var year = arr[0]; //获取当前日期的年份
        var month = arr[1]; //获取当前日期的月份
        var year2 = year;
        var month2 = parseInt(month) - 1;
        if (month2 == 0) {
          year2 = parseInt(year2) - 1;
          month2 = 12;
        }
        month2 = this.formatNumber(month2)
        var t2 = year2 + '-' + month2;
        resolve(t2)
      })
    },
    // 下一个月份
    getNextMonth(date) {
      return new Promise(resolve => {
        var arr = date.split('-');
        var year = arr[0]; //获取当前日期的年份
        var month = arr[1]; //获取当前日期的月份
        var year2 = year;
        var month2 = parseInt(month) + 1;
        if (month2 == 13) {
          year2 = parseInt(year2) + 1;
          month2 = 1;
        }
        month2 = this.formatNumber(month2)
        var t2 = year2 + '-' + month2;
        resolve(t2)
      })

    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    onScroll(event) {
      let top = event.detail
      for (let i in this.data.newHeightArr) {
        if (top < this.data.newHeightArr[i].height - distanceTop) {
          // console.log('top::::', i)
          this.setTopTime(this.data.newHeightArr[i].time)
          break
        }
      }
    },
    setTopTime(time) {
      // selectDate = time
      this.data.selectDate = time
      this.setData({
        selectYear: time.substring(0, time.indexOf('-')),
        selectMonth: time.substring(time.indexOf('-') + 1),
        monthAnimate: true
      })
    },
  }
})
